package net.csdra.wenhua.nanan.qiandao.service;

import net.csdra.wenhua.nanan.qiandao.domain.CheckIn;
import net.csdra.wenhua.nanan.qiandao.domain.CheckInRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.sql.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;
import java.util.UUID;

/**
 * Created by xiaomi on 2017/2/20.
 */
@Service
public class CheckInServiceImpl implements CheckInService {

    private static final Logger log = LoggerFactory.getLogger(CheckInServiceImpl.class);

    @Autowired
    CheckInRepository checkInRepository;

    @Override
    public CheckIn createCheckIn(CreateCheckIn createCheckIn) {
        Assert.notNull(createCheckIn.getUserId());
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(createCheckIn, checkIn);
        checkIn.setId(UUID.randomUUID().toString());
        checkIn.setCheckInTime(new Timestamp(Instant.now().toEpochMilli()));
        checkInRepository.save(checkIn);
        log.trace("createCheckIn: {}", checkIn);
        return checkIn;
    }

    @Override
    public CheckIn updateCheckIn(UpdateCheckIn updateCheckIn) {
        Assert.notNull(updateCheckIn.getCheckInId());
        CheckIn checkIn = checkInRepository.findOne(updateCheckIn.getCheckInId());
        Assert.notNull(checkIn);
        BeanUtils.copyProperties(updateCheckIn, checkIn);
        checkIn.setCheckInTime(new Timestamp(Instant.now().toEpochMilli()));
        checkInRepository.save(checkIn);
        return checkIn;
    }

    @Override
    public List<CheckIn> getCheckInListByUserId(String userId) {
        Assert.notNull(userId);
        return checkInRepository.findByUserIdOrderByCheckInTimeDesc(userId);
    }
}
